package com.framework.modules.job.task.yhbtask;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.entity.flow.FlowAccount;
import com.framework.entity.sys.SysAgent;
import com.framework.exception.RRException;
import com.framework.service.AgentInfoService;
import com.framework.service.AgentService;
import com.framework.service.FlowAccountService;
import com.framework.service.yhbservice.YhbCreditCardService;
import com.framework.service.yhbservice.YhbCurrentCountService;
import com.framework.service.yhbservice.YhbUserService;
import com.framework.service.yhbservice.YhbUserTerminalRelationService;
import com.framework.utils.string.StringUtil;
import com.framework.yhbEntity.currentcount.YhbCurrentCount;
import com.framework.yhbEntity.user.YhbCreditCard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 信用卡结算
 */
@Component("creditCardTask")
public class CreditCardTask {

        @Autowired
        private YhbCreditCardService yhbCreditCardService;

        @Autowired
        private YhbUserTerminalRelationService yhbUserTerminalRelationService;
        @Autowired
        private YhbCurrentCountService yhbCurrentCountService;

        @Autowired
        private AgentInfoService agentInfoService;
        @Autowired
        private YhbUserService yhbUserService;

        @Autowired
        private AgentService agentService;

        @Autowired
        private FlowAccountService flowAccountService;

        private Logger logger= LoggerFactory.getLogger(getClass());

        @Transactional(rollbackFor = Exception.class)
        public void settleCreditCard(){
                logger.info("-----------用户宝推荐办卡结算开始--------------");

                List<YhbCreditCard> list = yhbCreditCardService.selectList(new EntityWrapper<YhbCreditCard>()
                        .eq("card_state", 1)
                        .eq("is_settle", 0));
                for (YhbCreditCard yhbCreditCard :list) {

                        yhbCreditCard.setIsSettle(1);
                        yhbCreditCardService.updateById(yhbCreditCard);

                        BigDecimal amount = yhbCreditCardService.queryBankAmount(yhbCreditCard.getBankType());

                        BigDecimal yhbAmount = amount.multiply(new BigDecimal("0.70"));
                        logger.info("-----------结算了"+yhbAmount+"给"+yhbCreditCard.getUserId()+"--------------");
                        //70%给用户宝用户
                        yhbUserService.addAmount(yhbUserService.queryUserByUserId(yhbCreditCard.getUserId()),yhbAmount);

                        //记录流水
                        String accountId=verifyAccountId(StringUtil.getDateString(6));
                        YhbCurrentCount currentCount=new YhbCurrentCount();
                        currentCount.setRelationId(String.valueOf(yhbCreditCard.getCardId()));
                        currentCount.setAccountId(accountId);
                        currentCount.setAmount(yhbAmount);
                        currentCount.setIncomeType(6);
                        currentCount.setIncome(1);
                        currentCount.setCreateDate(new Date());
                        currentCount.setIsActivity(0);
                        currentCount.setMoney(amount);
                        yhbCurrentCountService.insert(currentCount);


                        //计算客户经理的分润
                        String userId = yhbCreditCard.getUserId();
                        //查出当前用户宝用户的机器的百易机具所属人数量
                        Integer count=yhbUserTerminalRelationService.querySnOwnerNum(userId);

                        //查出当前用户宝用户的机器的百易机具所属人列表
                        List<Long> agentIdList=yhbUserTerminalRelationService.querySnOwnerList(userId);
                        if(count.intValue()!=agentIdList.size()){
                                throw new RRException("9000","系统出错,数量与列表长度不同");
                        }
                        logger.info("-----------结算百易所属人开始--------------");

                        //20%均分给用户宝所有百易机器的所属人
                        //得出倍率
                        BigDecimal ownerRate=new BigDecimal("0.20")
                                .divide(new BigDecimal(String.valueOf(agentIdList.size())));
                        //增加所属人的分润
                        addAmountAndFlowAccount(yhbCreditCard, amount, ownerRate, agentIdList, ownerRate);

                        logger.info("-----------结算百易所属人结束--------------");

                        logger.info("-----------结算百易盟主开始--------------");
                        //获取所属人的顶级盟主
                        List<Long> topAgentList=new ArrayList<>();

                        for (Long agentId:agentIdList) {

                                SysAgent agent = agentService.queryAgentById(agentId);
                                SysAgent baseAgent = agentService.queryBasicAgentBydeptId(agent.getDeptId());
                                SysAgent topAgent = agentService.queryTopAgentBySubIdAndBase(agentId, baseAgent.getAgentId());
                                topAgentList.add(topAgent.getAgentId());
                        }

                        //去重
                        List<Long> topAgentList2=new ArrayList<>();
                        Set set=new HashSet();
                        for (Long top:topAgentList) {
                                if(set.add(top)){
                                    topAgentList2.add(top);
                                }
                        }

                        set=null;

                        //核算,顶级盟主共享10%
                        //20%均分给用户宝所有百易机器的所属人
                        //得出倍率
                        BigDecimal topRate=new BigDecimal("0.10")
                                .divide(new BigDecimal(String.valueOf(topAgentList2.size())));

                        addAmountAndFlowAccount(yhbCreditCard, amount, ownerRate, topAgentList2, topRate);
                        logger.info("-----------结算百易盟主结束--------------");

                }

                logger.info("-----------用户宝推荐办卡结算结束--------------");
        }

        private void addAmountAndFlowAccount(YhbCreditCard yhbCreditCard, BigDecimal amount, BigDecimal ownerRate, List<Long> topAgentList2, BigDecimal topRate) {
                for (Long topAgentId:topAgentList2) {

                        agentInfoService.addAmount(topAgentId,amount.multiply(topRate));
                        //流水
                        FlowAccount flowAccount=new FlowAccount();

                        String accountFlowId=verifyAccountId(StringUtil.getDateString(6));

                        flowAccount.setAccountFlowId(Long.valueOf(accountFlowId));
                        flowAccount.setAmount(amount.multiply(ownerRate));
                        flowAccount.setBelId(String.valueOf(yhbCreditCard.getCardId()));
                        flowAccount.setSupportType(2);
                        flowAccount.setAccountType(11);
                        flowAccount.setCreateTime(new Date());
                        flowAccount.setAgentId(topAgentId);
                        flowAccountService.insert(flowAccount);

                }
        }

        private String  verifyAccountId(String accountId){
                YhbCurrentCount t = yhbCurrentCountService.selectById(accountId);
                if(t!=null){
                        accountId= StringUtil.getDateString(6);
                        verifyAccountId(accountId);
                }
                return accountId;
        }
}
